<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { useElementSize, useWindowSize } from '@vueuse/core'
  import { WatchSizePropsType } from './types'
  import { WatchSizeStrategyConst } from './consts'

  defineOptions({
    name: 'SWatchSize'
  })

  const props = withDefaults(defineProps<WatchSizePropsType>(), {
    strategy: WatchSizeStrategyConst.SELF,
    widthUpdateHandler: () => {},
    heightUpdateHandler: () => {},
    immediate: true,
    disabled: false
  })

  const rootElRef = ref<HTMLDivElement | null>(null)
  const { width: rootElWidth, height: rootElHeight } = useElementSize(rootElRef)
  const { width: windowWidth, height: windowHeight } = useWindowSize()
  const getWidthResponsive = () =>
    props.strategy === WatchSizeStrategyConst.SELF ? rootElWidth.value : windowWidth.value
  const getHeightResponsive = () =>
    props.strategy === WatchSizeStrategyConst.SELF ? rootElHeight.value : windowHeight.value
  const handleWidthUpdate = (w: number) => {
    if (props.disabled) return
    props.widthUpdateHandler(w)
  }
  const handleHeightUpdate = (h: number) => {
    if (props.disabled) return
    props.heightUpdateHandler(h)
  }
  watch(getWidthResponsive, handleWidthUpdate, { immediate: props.immediate })
  watch(getHeightResponsive, handleHeightUpdate, { immediate: props.immediate })
</script>

<template>
  <div ref="rootElRef" class="s-watch-size">
    <slot></slot>
  </div>
</template>

<style lang="scss">
  @use './style' as *;
</style>
